// pyj
var express = require('express');
var router = express.Router();
var models = require('../models');
var _ = require('lodash');
var common = require('../core/utils/common');
var AppError = require('../core/app-error')

router.get('/:appName',  (req, res) => {
  var appName =_.trim(req.params.appName);
  models.Apps.findOne({where:{name:_.trim(appName)}}).then((package)=>{
    if (_.isEmpty(package)) {
      throw new AppError.AppError('no this app');
    }
    var rs = {
      appName:"",
      downloadURL: "",
      downloadUrl: "",
      description: "",
      isAvailable: false,
      isMandatory: false,
      packageHash: "",
      label: "",
      packageSize: 0,
      updateAppVersion: false,
      shouldRunBinaryVersion: false
    };
    models.Packages.findOne({where:{released_by:package.id},order:[['created_at', 'DESC']]})
      .then((packages) => {
        if (_.isEmpty(packages)) {
          throw new AppError.AppError('no this app');
        }
        rs.appName=appName;
        rs.downloadURL = common.getBlobDownloadUrl(_.get(packages, 'blob_url'));
        rs.downloadUrl = common.getBlobDownloadUrl(_.get(packages, 'blob_url'));
        rs.description = _.get(packages, 'description', '');
        rs.isAvailable = true;
        rs.isMandatory = _.eq(packages.is_mandatory, 1) ? true : false;
        rs.packageHash = _.get(packages, 'package_hash', '');
        rs.label = _.get(packages, 'label', '');
        rs.packageSize = _.get(packages, 'size', 0);
        rs.shouldRunBinaryVersion = false;
        res.send({appinfo: rs});
      })
  }).catch(e => {
    if (e instanceof AppError.AppError) {
      res.status(406).send(e.message);
    } else {
      next(e);
    }
  });
});

module.exports = router;
